# field_management/views.py
from django.urls import reverse_lazy
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib import messages # For success messages
from django.utils.translation import gettext as _ # Use gettext for messages

from .models import Field
from .forms import FieldForm
from planting_records.models import PlantingRecord # Import related model
from django.http import JsonResponse # Import JsonResponse
from django.core.serializers import serialize
import json
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
# Mixin to check ownership
class OwnerRequiredMixin(UserPassesTestMixin):
    def test_func(self):
        obj = self.get_object()
        # For Field model, owner is directly on the object
        if isinstance(obj, Field):
            return self.request.user == obj.owner
        # Add checks for other models if needed
        return False

    def handle_no_permission(self):
        messages.error(self.request, _("您无权访问此页面。"))
        # Redirect to a safe page, like the list view or home
        # Adjust the redirect based on model context if necessary
        if isinstance(self.get_object(), Field):
             return redirect(reverse_lazy('field_management:field_list'))
        return redirect(reverse_lazy('home')) # Fallback redirect


class FieldListView(LoginRequiredMixin, ListView):
    model = Field
    template_name = 'field_management/field_list.html'
    context_object_name = 'fields'
    paginate_by = 10

    def get_queryset(self):
        return Field.objects.filter(owner=self.request.user).order_by('name')


class FieldDetailView(LoginRequiredMixin, OwnerRequiredMixin, DetailView):
    model = Field
    template_name = 'field_management/field_detail.html'
    context_object_name = 'field'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['planting_records'] = PlantingRecord.objects.filter(
            field=self.get_object()
        ).order_by('-planting_date')[:10] # Show recent records
        context['page_title'] = _("田块详情") + f": {self.object.name}" # Example title
        return context


class FieldCreateView(LoginRequiredMixin, CreateView):
    model = Field
    form_class = FieldForm
    template_name = 'field_management/field_form.html'
    # success_url = reverse_lazy('field_management:field_list') # Or use get_absolute_url

    def form_valid(self, form):
        form.instance.owner = self.request.user
        messages.success(self.request, _("田块 '{name}' 已成功添加。").format(name=form.instance.name))
        return super().form_valid(form)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['view_title'] = _('添加新田块')
        return context


class FieldUpdateView(LoginRequiredMixin, OwnerRequiredMixin, UpdateView):
    model = Field
    form_class = FieldForm
    template_name = 'field_management/field_form.html'

    def form_valid(self, form):
        messages.success(self.request, _("田块 '{name}' 已成功更新。").format(name=self.object.name))
        return super().form_valid(form)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['view_title'] = _('编辑田块') + f': {self.object.name}'
        return context


class FieldDeleteView(LoginRequiredMixin, OwnerRequiredMixin, DeleteView):
    model = Field
    template_name = 'field_management/field_confirm_delete.html'
    success_url = reverse_lazy('field_management:field_list')

    def form_valid(self, form):
        # Use form_valid to add the success message before deletion
        messages.success(self.request, _("田块 '{name}' 已成功删除。").format(name=self.object.name))
        return super().form_valid(form)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['view_title'] = _('删除确认')
        return context

@login_required # Ensure only logged-in users can access
def field_locations_json(request):
    """
    Returns a JSON list of fields owned by the user with valid coordinates.
    """
    # Filter fields owned by the current user that have BOTH latitude and longitude
    fields_with_coords = Field.objects.filter(
        owner=request.user,
        latitude__isnull=False,
        longitude__isnull=False
    ).values('pk', 'name', 'latitude', 'longitude', 'area') # Select necessary fields

    # Convert QuerySet to a list of dictionaries
    field_list = list(fields_with_coords)

    # Add detail URL to each field dictionary
    for field in field_list:
        field['detail_url'] = reverse('field_management:field_detail', kwargs={'pk': field['pk']})
        # Ensure Decimal fields are converted to strings or floats for JSON compatibility
        field['latitude'] = float(field['latitude'])
        field['longitude'] = float(field['longitude'])
        field['area'] = float(field['area']) # Also convert area

    return JsonResponse(field_list, safe=False) # safe=False allows sending a list